package com.easysoft.framework.menu.service;

import com.easysoft.commons.utils.DateTimeUtils;
import com.easysoft.commons.utils.UUIDUtils;
import com.easysoft.framework.annotation.jdbc.DataSource;
import com.easysoft.framework.beans.Page;
import com.easysoft.framework.menu.mapper.SysMenuMapper;
import com.easysoft.framework.menu.mapper.SysMenuMapperExtd;
import com.easysoft.framework.menu.model.SysMenu;
import com.easysoft.framework.menu.model.SysMenuQuery;
import com.easysoft.framework.menu.model.SysMenuView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("service.SysMenuService")
public class SysMenuService {
    private final static Logger logger = LoggerFactory.getLogger(SysMenuService.class);

    @Autowired
    @Qualifier("mapper.SysMenuMapperExtd")
    private SysMenuMapperExtd sysMenuMapperExtd;

    @Autowired
    @Qualifier("mapper.SysMenuMapper")
    private SysMenuMapper sysMenuMapper;

    /**
     * 菜單查詢模塊
     *
     * @param page  請求參數
     * @param query 查詢條件
     * @return
     */
    @DataSource(DataSource.SLAVE)
    public List<SysMenuView> selectSysMenuByPage(Page page, SysMenuQuery query) {
        int maxRow = sysMenuMapperExtd.selectCountAllSysMenu(query);
        page.setMaxRow(maxRow);

        if (maxRow == 0) {
            return new ArrayList<SysMenuView>();
        }
        return sysMenuMapperExtd.selectSysMenuByPage(page, query);
    }

    @DataSource(DataSource.MASTER)
    public int addSysMenu(SysMenu sysMenu) {

        return sysMenuMapper.insertSelective(sysMenu);
    }

    @DataSource(DataSource.MASTER)
    public int updateSysMenuById(SysMenu sysMenu) {

        return sysMenuMapper.updateByPrimaryKeySelective(sysMenu);
    }


    /**
     * 得到分好层级关系的菜单列表
     *
     * @param userId 用户ID，可传空，传空查询启用的菜单，传ID按用户权限查询菜单
     * @return
     */
    public List<Map<String, Object>> getSysMenuTree(String userId) {
        List<Map<String, Object>> rootList = null;
        List<SysMenuView> sysMenuList = null;

        if (userId == null) {
            sysMenuList = sysMenuMapperExtd.selectAllSysMenuByIsEnable(0);
        } else {
            sysMenuList = sysMenuMapperExtd.selectEnableSysMenuByUserId(userId);
        }

        if (sysMenuList.size() == 0) {
            return rootList;
        }

        Map<String, List<Map<String, Object>>> rawMap = new HashMap<String, List<Map<String, Object>>>();
        for (SysMenu menu2 : sysMenuList) {
            Map<String, Object> menuMap = new HashMap<String, Object>();
            String id = String.valueOf(menu2.getId());
            menuMap.put("id", id);
            menuMap.put("text", menu2.getMenuName());
            // 子节点
            String parentID = String.valueOf(menu2.getParentId());
            Map<String, Object> attributes = new HashMap<String, Object>();
            attributes.put("parentId", menu2.getParentId());
            attributes.put("menuHref", menu2.getMenuHref());
            attributes.put("menuCode", menu2.getMenuCode());
            attributes.put("mid", menu2.getMid());
            attributes.put("menuIcon", menu2.getMenuIcon());
            menuMap.put("attributes", attributes);
            List<Map<String, Object>> tempList = rawMap.get(parentID);
            if (null == tempList) {
                tempList = new ArrayList<Map<String, Object>>();
                rawMap.put(parentID, tempList);
            }
            tempList.add(menuMap);
        }
        rootList = rawMap.get("0");
        for (Map<String, Object> m : rootList) {
            addChild(rawMap, m);
        }

        return rootList;

    }

    /**
     * 循环迭代添加子菜单
     *
     * @param rawMap
     * @param m
     */
    @SuppressWarnings("unchecked")
    private void addChild(Map<String, List<Map<String, Object>>> rawMap, Map<String, Object> m) {
        List<Map<String, Object>> parentList = rawMap.get(m.get("id"));
        if (parentList != null) {
            m.put("state", "open");
            m.put("children", parentList);
            for (Map<String, Object> menu : (List<Map<String, Object>>) m.get("children")) {
                addChild(rawMap, menu);
            }
        }
    }

    public int saveMenu(SysMenu sysMenu) {

        // 生成主键

        sysMenu.setCreateTime(DateTimeUtils.getCurrentDate());
        sysMenu.setId(UUIDUtils.getUUID());
        // 保存数据
        return sysMenuMapper.insertSelective(sysMenu);
    }

    @DataSource(DataSource.MASTER)
    public int deleteSysMenu(String id, String operUser) {

        int result = 0;

        logger.info("Call MenuService.deleteMenu({}, {})", id, operUser);

        // 先查询是否有子菜单
        int childCount = sysMenuMapperExtd.selectCountByParentId(id);

        // 没有子菜单才可以删除
        if (childCount == 0) {
            result = sysMenuMapper.deleteByPrimaryKey(id);
        } else {
            result = -1;
        }

        return result;
    }

    @DataSource(DataSource.MASTER)
    public int updateSysMenu(SysMenu sysMenu, String operUser) {

        sysMenu.setOperator(operUser);

        return sysMenuMapper.updateByPrimaryKey(sysMenu);
    }

    @DataSource(DataSource.SLAVE)
    public SysMenu selectMenuByPrimaryKey(String id) {
        return sysMenuMapper.selectByPrimaryKey(id);
    }

    @DataSource(DataSource.SLAVE)
    public List<SysMenuView> selectAllMenu(Page page, SysMenuQuery query) {
        int maxRow = sysMenuMapperExtd.selectCountAllSysMenu(query);
        page.setMaxRow(maxRow);

        if (maxRow == 0) {
            return new ArrayList<SysMenuView>();
        }

        return sysMenuMapperExtd.selectSysMenuByPage(page, query);
    }

    @DataSource(DataSource.SLAVE)
    public List<SysMenuView> selectSysMenuByLevel(int menuLevel) {
        return sysMenuMapperExtd.selectSysMenuByLevel(menuLevel);
    }

    @DataSource(DataSource.SLAVE)
    public List<SysMenuView> selectSysEnableMenuByUserId(String userId) {
        return sysMenuMapperExtd.selectEnableSysMenuByUserId(userId);
    }

    @DataSource(DataSource.SLAVE)
    public List<SysMenuView> checkMid(int mid) {
        return sysMenuMapperExtd.checkMid(mid);
    }

}
